#/usr/bin/env python
#author  cwc
import os
import logging
import argparse
import os
import json

from kmxclient.kmxclient import KMXPlatform
from analysis.simulation import Simulation,BigNdarray

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename='simulator.log',
                    filemode='w')

if __name__ == '__main__':
    args = argparse.ArgumentParser(description='args for taskparser')
    args.add_argument('--create-metadata', action='store_true')
    args.add_argument('--big-ndarray', action='store_true')
    args.add_argument('--kmx-csv', action='store_true')
    args.add_argument('--push', action='store_true')

    parser = args.parse_args()
    sim_path = os.getenv('SIMULATOR_PATH')
    if parser.create_metadata:
        logging.info("begin create_metadata")
        simulator = Simulation(sim_path)
        simulator.files_analysis()
        simulator.varibles_analysis()
        simulator.create_fieldgroup()
        simulator.create_assets()
        logging.info("end create_metadata")

    if parser.big_ndarray:
        logging.info("begin big_ndarray")

        bigndarray = BigNdarray(sim_path)
        bigndarray.bigndarray()
        logging.info("end big_ndarray")

    if parser.kmx_csv:
        logging.info("begin kmx_csv")
        bigndarray = BigNdarray(sim_path)
        bigndarray.kmxcsv()
        logging.info("end kmx_csv")

    if parser.push:
        kmxclient = KMXPlatform(os.getenv('KMX_SDM_API'))

        fg_saved_path = os.getenv('FIELDGROUP_SAVED_PATH')
        assets_saved_path = os.getenv('ASSETS_SAVED_PATH')

        for f in os.listdir(fg_saved_path):
            real_path = os.path.join(fg_saved_path,f)
            if os.path.isfile(real_path):
                data = json.dumps(json.load(open(real_path)))
                kmxclient.push_dt(data)

        for f in os.listdir(assets_saved_path):
            real_path = os.path.join(assets_saved_path,f)
            print real_path
            if os.path.isfile(real_path):
                data = json.dumps(json.load(open(real_path)))
                kmxclient.push_d(data)